package com.bluexmicro.example.page.main

import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.net.Uri
import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.PopupProperties
import androidx.navigation.NavHostController
import com.bluexmicro.example.R
import com.bluexmicro.example.page.custom.*
import com.bluexmicro.example.page.main.ExtraType.*
import com.bluexmicro.example.route.Route

@Composable
fun MainPage(navHostController: NavHostController, mainViewModel: MainViewModel) {
    val items = remember {
        mainViewModel.tasks
    }
    val device = remember {
        mainViewModel.selectedDevice
    }
    val context = LocalContext.current
    var fastMode by remember {
        mainViewModel.fastMode
    }
    val uiEnable = remember {
        mainViewModel.uiEnable
    }
    Scaffold(
        topBar = {
            MyTopBar { type ->
//                if (uiEnable.value) {
//                    val routePath = when (type) {
//                        TRANSACTION -> Route.OTA_TRANSACTION.key
//                        else -> {}
//                    }
//                    navHostController.navigate(routePath)
//                }
            }
        },
    ) {
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(it)
                .padding(horizontal = 16.dp)
        ) {
            item {
                Row(
                    modifier = Modifier.padding(vertical = 8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text("快速模式")
                    KeepScreenOnView(keepOn = !uiEnable.value, modifier = Modifier.weight(1f))
                    Switch(checked = fastMode, onCheckedChange = {
                        fastMode = it
                        mainViewModel.saveFastMode(context, it)
                    }, enabled = uiEnable.value)
                }
                Divider(color = Color.LightGray, thickness = Dp.Hairline)
                StepTitle(1, "选择固件或者素材", items.isNotEmpty())
                StepContent {
                    Text(
                        "请一定要与工程师确认待升级文件是「固件」还是「素材」，素材(UI/Font)是需要填入地址的，否则会导致设备异常",
                        style = MaterialTheme.typography.labelMedium,
                        color = Color.Red,
                        modifier = Modifier.padding(bottom = 8.dp)
                    )
                }
            }
            itemsIndexed(items) { _, item ->
                StepContent {
                    OtaTaskItemView(item, false, onStart = { model -> }) {
                        mainViewModel.removeFile(context, it)
                    }
                }
            }
            item {
                StepContent {
                    val pickFileEnable = uiEnable.value && (items.isEmpty() || fastMode)
                    OutlinedButton(onClick = {
                        if (pickFileEnable) {
                            navHostController.navigate(Route.OTA_PICK_FILE.key)
                        }
                    }, enabled = pickFileEnable) {
                        Text("选择")
                    }
                }
            }
            item {
                StepTitle(2, "选择设备", device.value != null)
                StepContent {
                    OutlinedButton(onClick = {
                        if (uiEnable.value) {
                            navHostController.navigate(Route.OTA_PICK_PERIPHERAL.key)
                        }
                    }, enabled = uiEnable.value) {
                        val txt = device.value?.address ?: "选择"
                        Text(txt)
                    }
                }
            }
            item {
                val payload = if (fastMode) "快速升级" else "普通升级"
                val startEnable = uiEnable.value && items.isNotEmpty() && device.value != null
                StepTitle(3, payload, false)
                StepContent {
                    Button(onClick = {
                        if (startEnable) {
                            mainViewModel.startUpdate(context)
                        }
                    }, enabled = startEnable) {
                        Text("开始")
                    }
                }
                TipView(uiEnable.value)
            }
            item {
                Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxWidth()) {
                    Button(onClick = {
                        navHostController.navigate(Route.HELP.key)
                    }) {
                        Text("使用帮助")
                    }
                }
            }
        }
    }
}

@Composable
fun MyTopBar(onMenuSelected: (item: ExtraType) -> Unit) {
    TopAppBar(
        title = {
            Text("BX OTA", color = MaterialTheme.colorScheme.onPrimary)
        },
        backgroundColor = MaterialTheme.colorScheme.primary,
        elevation = 5.dp,
        actions = {
//            ExtraDropdownMenuButton(onMenuSelected = onMenuSelected)
        }
    )
}


enum class ExtraType(val key: String) {
    TRANSACTION("自定义顺序"), PARTITION_TABLE("分区表"), ASSET("Asset Update"), CONNECT_DEVICE("连接设备")
}

@Composable
fun ExtraDropdownMenuButton(onMenuSelected: (item: ExtraType) -> Unit) {
    var expand by remember {
        mutableStateOf(false)
    }
    Column {
        IconButton(onClick = {
            expand = !expand
        }) {
            Icon(
                painter = painterResource(id = R.drawable.ic_more),
                null,
                tint = MaterialTheme.colorScheme.onPrimary,
                modifier = Modifier.size(24.dp)
            )
        }
        DropdownMenu(
            expanded = expand,
            onDismissRequest = {
                Log.e("ccm", "执行了onDismissRequest")
                expand = false
            },
            offset = DpOffset(8.dp, 16.dp),
            properties = PopupProperties(),
            modifier = Modifier.background(color = Color.White)
        ) {
            values().forEach { type ->
                ExtraDropdownMenuItem(text = type.key) {
                    onMenuSelected.invoke(type)
                    expand = false
                }
                Divider(
                    modifier = Modifier.fillMaxWidth(),
                    color = Color.LightGray,
                    thickness = Dp.Hairline
                )
            }
        }
    }
}

@Composable
fun ExtraDropdownMenuItem(text: String, onClick: () -> Unit) {
    DropdownMenuItem(
        onClick = onClick,
        enabled = true,
    ) {
        androidx.compose.material.Text(text = text)
    }
}

@Composable
fun TipView(enable: Boolean) {
    Column {
        Spacer(modifier = Modifier.height(16.dp))
        Row(verticalAlignment = Alignment.CenterVertically) {
            Divider(modifier = Modifier.weight(1f))
            Text(
                "Tips",
                modifier = Modifier.padding(16.dp),
                style = MaterialTheme.typography.labelSmall
            )
            Divider(modifier = Modifier.weight(1f))
        }

        Text(
            "普通模式: 单次只能升级一个文件，最大吞吐量为20字节。",
            style = MaterialTheme.typography.labelSmall
        )
        Text(
            "快速模式: 支持多任务，最大吞吐量等于MTU长度。",
            style = MaterialTheme.typography.labelSmall
        )
        Text(
            "设备不能同时支持普通模式和快速模式，升级前请与工程师确认待升级设备支持哪一种模式。",
            style = MaterialTheme.typography.labelSmall
        )
        Spacer(modifier = Modifier.height(16.dp))
        Row {
            Spacer(modifier = Modifier.weight(1f))
            VersionTipText(enable)
            Spacer(modifier = Modifier.weight(1f))
        }
    }
}

@Composable
fun VersionTipText(enable: Boolean) {
    val context = LocalContext.current
    val version = try {
        val info = context.packageManager.getPackageInfo(context.packageName, 0)
        info.versionName
    } catch (ignore: Exception) {
        "Unknown Version"
    }
    val tmp = if (isDebug(context)) "（Debug）" else ""
    OutlinedButton(enabled = enable, onClick = {
        //OutlinedButton在disable状态下能触发onclick
        if (enable) {
            val uri = Uri.parse("https://www.pgyer.com/C3EW");    //设置跳转的网站
            val intent = Intent(Intent.ACTION_VIEW, uri)
            context.startActivity(intent)
        }
    }, shape = RoundedCornerShape(64.dp)) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text("下载新版本", style = MaterialTheme.typography.labelMedium)
            Text(
                "当前版本: $version$tmp",
                style = MaterialTheme.typography.labelSmall,
                color = MaterialTheme.colorScheme.onBackground
            )
        }
    }

}

private fun isDebug(context: Context): Boolean {
    return context.applicationInfo != null && (context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0)
}




